<template>
  <div>
    <input type="file" @change="changeFile">
    <el-image style="width: 100px; height: 100px"
              src="http://127.0.0.1:9000/test-bucket/808ed9490b594cf695a3d4c1f2600f8b">
      <template #placeholder>
        <div v-loading></div>
      </template>
    </el-image>
    <el-button @click="downloadFile">下载文件</el-button>
  </div>
</template>

<script>
import { uploadImgUrl, downloadUrl, generateUploadIdUrl, partUploadUrl } from '@/api/api'
import { post, commonPostDownloadFile, getDownloadFile } from '@/utils/httpRequest'
import { ref } from 'vue'

export default {
  name: 'personFile',
  setup () {
    const file = ref(null)
    const changeFile = async (e) => {
      // await sliceUpload(e.target.files[0])
      console.log(e)
      const formData = new FormData()
      formData.append('file', e.target.files[0])
      const result = await post(uploadImgUrl, formData)
      if (result.code === 200) {
        console.log(result.data)
      }
    }
    const sliceUpload = async (file) => {
      const result0 = await post(generateUploadIdUrl, {})
      let uploadId = null
      if (result0.code === 200) {
        uploadId = result0.data
      }
      console.log(file)
      // 文件大小
      const fileSize = file.size
      // 切片大小 1K
      const chunkSize = 1024 * 1024
      // 切片总数
      const chunkTotal = Math.ceil(fileSize / chunkSize)
      await partUpload(uploadId, file, chunkTotal, 0, chunkSize)
      console.log('切片总数', chunkTotal)
    }
    const partUpload = async (uploadId, file, chunkTotal, currentChunk, chunkSize) => {
      if (currentChunk < chunkTotal) {
        const formData = new FormData()
        formData.append('file', file.slice(currentChunk * chunkSize, (currentChunk + 1) * chunkSize))
        formData.append('generateUploadId', uploadId)
        formData.append('chunkTotal', chunkTotal)
        formData.append('currentChunk', currentChunk)
        const result = await post(partUploadUrl, formData)
        if (result.code === 200) {
          await partUpload(uploadId, file, chunkTotal, currentChunk + 1, chunkSize)
        }
      }
    }
    const downloadFile = async () => {
      await commonPostDownloadFile(downloadUrl, { fileId: '1499391012202770434' })
    }
    const getFile = async () => {
      const result = await getDownloadFile('file/getFileInputStream/1504083510070226946', {})
      console.log(result.data)
      file.value = URL.createObjectURL(new Blob([result.data]))
    }
    getFile()
    return {
      file,
      sliceUpload,
      downloadFile,
      changeFile,
      uploadImgUrl
    }
  }
}
</script>

<style scoped>

</style>
